﻿package net.wangit.framework.expression;

import net.wangit.context.ActionContext;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;
/**
 * SQL表达式
 * @author watson
 *
 */
public class SQLExpression {

	private static final String PREFIX = "$SQL[[";
	private static final String SUFFIX = "]]";
	protected static final String NULL_VALUE = "$NULL{}";
	private static final String MAKE_NULL = " and 1=2 ";

	public SQLExpression() {
	}

	public static final String resolve(ActionContext ac, String expression) {
		if (Checker.isEmpty(expression))
			return expression;
		StringBuffer result = new StringBuffer();
		String attribute;
		while ((attribute = StringUtil.find(expression, SQLExpression.PREFIX,
				SQLExpression.SUFFIX)) != null) {
			int index = expression.indexOf((new StringBuilder(
					SQLExpression.PREFIX)).append(attribute).append(
					SQLExpression.SUFFIX).toString());
			result.append(expression.substring(0, index)).append(
					getValue(ac, attribute));
			expression = expression.substring(index + attribute.length()
					+ SQLExpression.PREFIX.length()
					+ SQLExpression.SUFFIX.length());
		}
		result.append(expression);
		return result.toString();
	}

	protected static String getValue(ActionContext ac, String attribute) {
		attribute = ConstantExpression.resolve(attribute);
		attribute = VariableExpression.resolve(attribute);
		attribute = UserExpression.resolve(ac, attribute);
		attribute = OrgExpression.resolve(ac, attribute);
		attribute = RequestExpression.resolve(ac, attribute,
				SQLExpression.NULL_VALUE, false);
		attribute = SessionExpression.resolve(ac, attribute,
				SQLExpression.NULL_VALUE, false);
		attribute = Request2SessionExpression.resolve(ac, attribute,
				SQLExpression.NULL_VALUE, false);
		if (attribute.indexOf(SQLExpression.NULL_VALUE) >= 0)
			return SQLExpression.MAKE_NULL;
		else
			return attribute;
	}
}
